$(function () {
    $("#jqGrid").Grid({
        url: '../toolsstorepos/list',
        loadError: function (jqXHR, textStatus, errorThrown) {
            // 目前只处理查询过多的条件
            iview.Message.error("匹配当前查询条件的记录数过多，请进一步细化查询条件！");
            return;
        },
        rownumWidth: 50,
        colModel: [
            {label: '工装名称', name: 'toolsName', index: 'toolsName', width: 80},
            {label: '型号规格', name: 'spec', index: 'spec', width: 80},
            {label: '工装编码', name: 'toolsCode', index: 'TOOLS_CODE', width: 80,frozen: true},
            {label: '图号', name: 'mapNo', index: 'MAP_NO', width: 120,frozen: true},
            {label: '工装类别', name: 'typeName', index: 'TOOLS_TYPE', width: 80},
            {label: '仓库名称', name: 'storeName', width: 120},
            {label: '库位', name: 'postion', index: 'POSTION', width: 60},
            {label: '库存数', name: 'storeNum', index: 'STORE_NUM', width: 40},
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
            {label: 'storeId', name: 'storeId', index: 'storeId', hidden: true},
        ]
    });
    vm.getStore();
});

var ztree;

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
    callback: {
        onClick: function () {
            // 重置仓库类别和仓库ID
            vm.q.storeType = '';
            vm.q.storeId = '';
            var node = ztree.getSelectedNodes();
            //选择上级菜单
            if (node[0].id.indexOf('AAA') !== -1) {

            }else if (node[0].id.indexOf('BBB') !== -1) {
                vm.q.storeType = 2;
            }else if (node[0].id.indexOf('CCC') !== -1) {
                vm.q.storeType = 1;
            }else {
                vm.q.storeId = node[0].id;
            }
            vm.pageNum = 1;
            vm.reload();
        }
    }
};

// 校验可退库数方法
function validateExchangeNum(rule, value, callback) {
    if (!Number.isInteger(+value)) {
        callback(new Error('输入数字'));
    } else{
        let backNum = parseInt(value);
        if(backNum <= 0){
            callback(new Error('移库数不得小于0！'));
        }else if(vm.spareStorePos.storeNum < backNum){
            callback(new Error('移库数不得大于' + vm.spareStorePos.storeNum));
        }else{
            callback();
        }
    }
};

let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        spareStorePos: {
            storeName: '',
            postion: '',
            spareName: '',
            storeNum: '',
            id: '',
            exchangeNum:0, // 期望转移库存数
            targetStoreId: '',// 目标仓库ID
            targetStoreName: '', // 目标仓库名称
            targetId: '', // 目标库位ID
            targetPostion: '', // 目标库位
            spareCode: '' // 备件编码
        },
        ruleValidate: {
            exchangeNum: [
                { required: true, validator: validateExchangeNum, trigger: 'blur'}
            ]
        },
        q: {
            name: '', // 名称
            mapNo: '', // 图号
            type: '', // 型号规格
            storeId:'', // 所在仓库ID
            storeType: '' //仓库类别：1：ERP库 2:线边库
        },
        pageNum: 1,
        storePosList:[], // 备件库位列表
        showOther: false
    },
    methods: {
        //选择入库仓库
        getStoreHouse: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-institution"></i> 选择仓库',
                content: '../sys/storeHouseSelect.html?type=2',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getStoreHouse();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.spareStorePos.targetStoreId = res.id;
                        vm.spareStorePos.targetStoreName = res.name;
                        //获取位置列表
                        vm.getStorePos();
                    }
                }
            })
        },
        // 根据仓库ID和备件编码拉取备件已有库位信息
        getStorePos: function () {
            // var storeId =
            Ajax.request({
                url: "../sparestorepos/queryAll",
                params: {"storeId": vm.spareStorePos.targetStoreId ,"partCode":vm.spareStorePos.spareCode},
                async: true,
                successCallback: function (r) {
                    vm.storePosList = r.list;
                }
            });
        },
        showLoc: function (type) {
            vm.spareStorePos.targetPostion = '';
            vm.spareStorePos.targetId = '';
            vm.showOther = type==0;
        },
        // 备件移库操作
        exchangeStorePos: function(){
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.getInfo(id);
            if(vm.spareStorePos.storeNum <= 0){
                alert("只有库存数大于0的备件才可以执行移库操作");
                return;
            }
            // 初始化表单信息
            vm.spareStorePos.targetStoreId = '';
            vm.spareStorePos.targetStoreName = '';
            vm.spareStorePos.targetId = '';
            vm.spareStorePos.targetPostion = '';

            // 库存转移
            vm.showList = false;
            vm.title = "备件移库";
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.spareStorePos = {
                delFlag: '',
                storeNum: '',
                postion: '',
                spareCode: '',
                storeId: '',
                id: '',
            };
        },
        update: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {
            if(!vm.spareStorePos.id){
                iview.Message.error("当前库位必填");
                return;
            }
            if(!vm.spareStorePos.targetId && !vm.spareStorePos.targetPostion){
                iview.Message.error("目标库位信息必填！");
                return;
            }
            Ajax.request({
                url: '../sparestorepos/exchange',
                params: JSON.stringify(vm.spareStorePos),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../sparestorepos/info/" + id,
                async: false,
                successCallback: function (r) {
                    vm.spareStorePos.storeName = r.spareStorePos.storeName;
                    vm.spareStorePos.postion = r.spareStorePos.postion;
                    vm.spareStorePos.spareName = r.spareStorePos.spareName;
                    vm.spareStorePos.storeNum = r.spareStorePos.storeNum;
                    vm.spareStorePos.exchangeNum = r.spareStorePos.storeNum;
                    vm.spareStorePos.spareCode = r.spareStorePos.spareCode;
                    vm.spareStorePos.id = r.spareStorePos.id;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;

            // 清空postData缓存数据
            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var queryParam = {};
            if(vm.q.name){
                queryParam.name = vm.q.name;
            }
            if(vm.q.mapNo){
                queryParam.mapNo = vm.q.mapNo;
            }
            if(vm.q.type){
                queryParam.type = vm.q.type;
            }
            if(vm.q.storeId){
                queryParam.storeId = vm.q.storeId;
            }
            if(vm.q.storeType){
                queryParam.storeType = vm.q.storeType;
            }
            var page = (vm.pageNum == 1)? vm.pageNum : $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: queryParam,
                page: page
            }).trigger("reloadGrid");
            vm.pageNum = $("#jqGrid").jqGrid('getGridParam', 'page');
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                name: '', // 名称
                mapNo: '', // 图号
                type: '', // 型号规格
                storeId:'', // 所在仓库ID
                storeType: '' //仓库类别：1：ERP库 2:线边库
            };
            ztree.cancelSelectedNode();
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        getStore: function () {
            //加载树
            Ajax.request({
                url: "../storehouse/allList?moduleType=2",
                async: true,
                successCallback: function (r) {
                    var list = r.list;
                    var tree = [{id: 'AAA', name: '仓库', parentId: '0'},
                        {id: 'BBB', name: '线边库', parentId: 'AAA'},
                        {id: 'CCC', name: 'ERP库', parentId: 'AAA'}];
                    for (let i = 0; i < list.length; i++) {
                        var stoType = list[i].storeType;
                        if (stoType == "1") {
                            list[i].parentId = 'CCC'; //ERP库
                        } else {
                            list[i].parentId = 'BBB'; //线边库
                        }
                        tree.push(list[i]);
                    }
                    ztree = $.fn.zTree.init($("#storeTree"), setting, tree);
                    ztree.expandAll(true);
                }
            });
        },
        detailsInfo:function (code){
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 记录信息',
                content: '../spare/spareRoom.html?code=' + code
            })
        },
        handleBeforeUploadExcel: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleImportExcelSuccess: function (res, file) {
            if (res.code == 0) {
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.err
                })
            }
        },
        handleExcelFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleImportExcelError: function (err, file) {
            alert('导入失败');
        }
    }
});
